/*
 *
 *  Copyright (C) THL A29 Limited, a Tencent company. All rights reserved.
 *  SPDX-License-Identifier: Apache-2.0
 *
 */

import { IChainBrowserTxDetail } from './common/apis/chains/interface';
import { Base64 } from 'js-base64';

export type WebWorkerRequest<T> = {
  type: 'deal-detail';
  data: T;
};

export type WebWorkerResponse<T> = WebWorkerRequest<T>;

(self as DedicatedWorkerGlobalScope).onmessage = function ({ data }) {
  const req = JSON.parse(data) as WebWorkerRequest<any>;
  const res = {
    type: req.type,
    data: {},
  };

  if (isDealDetail(req)) {
    res.data = {
      ContractParameters: req.data.ContractParameters?.map(param => {
        // CONTRACT_BYTECODE内容在解码后达到15MB，造成渲染极其卡顿且没有可读性，因此跳过解码
        if (param.key !== 'CONTRACT_BYTECODE') {
          param.value = Base64.decode(param.value);
        } else {
          param.value = param.value.substring(0, 256);
          param.fullData = param.value;
        }
        return param;
      }),
      ContractResult: req.data.ContractResult ? Base64.decode(req.data.ContractResult) : '',
    };
  }
  postMessage(res);
};


function isDealDetail(req: WebWorkerRequest<any>): req is WebWorkerRequest<IChainBrowserTxDetail> {
  return req.type === 'deal-detail';
}
